from typing import Dict, Any
from fastapi import WebSocket
from datetime import datetime
from app.db.session import get_db
from app.db.models.user import User, Friend, Apply
from app.db.models.chat import Message as DBMessage, Room, RoomMember
from app.schemas.message import MessageCreate
from sqlalchemy.orm import Session
import traceback
import asyncio
from .message import MessageService
"""

前端抓包发现type=4的消息格式如下
{
    "type": 4,
    "body": {
        "id": 509,
        "name": "我的好友",
        "fixed": 1,
        "friends": [
            {
                "id": 142,
                "userId": 550,
                "nickname": "test222",
                "sex": 2,
                "online": 1,
                "email": "m51777888@163.com",
                "lastAt": 1747542048000,
                "createdAt": 1747539756000
            }
        ]
    }
}
type=0的消息格式如下
{
    "type": 0
}
type=3的消息格式如下
{
    "type": 3,
    "body": {
        "id": 195,
        "userId": 513,
        "content": "我是666ren，想添加你为好友！",
        "type": 0,
        "targetId": 550,
        "status": 0,
        "createdAt": 1747542176000,
        "user": {
            "id": 513,
            "nickname": "666ren",
            "sex": 0,
            "online": 1
        }
    }
}
type=23的消息格式如下
{
    "type": 23,
    "body": 513
}
type=1的消息格式如下
{
    "type": 1,
    "body": {
        "id": 638,
        "roomId": 70,
        "userId": 550,
        "message": {
            "userId": 513,
            "nickname": "666ren",
            "sex": 0,
            "id": 2311,
            "type": 0,
            "text": "dd😗",
            "status": 1,
            "createdAt": 1747542429000
        },
        "friend": {
            "id": 143,
            "userId": 513,
            "nickname": "666ren",
            "sex": 0,
            "online": 1
        }
    }
}
websocket主要用于:
- 即时消息传递
- 好友状态同步
- 音视频通话信令
- 系统通知推送
- 在线状态维护
- 心跳保活
"""
class WebSocketHandler:
    def __init__(self):
        self.active_connections: Dict[int, WebSocket] = {}
        self.last_heartbeat: Dict[int, datetime] = {}
        self.connection_lock = asyncio.Lock()
        self.heartbeat_task = None
        self.connection_status: Dict[int, bool] = {}  # 新增：跟踪连接状态
        
    async def setup(self):
        """设置WebSocketHandler，启动心跳检测任务"""
        if self.heartbeat_task is None:
            self.heartbeat_task = asyncio.create_task(self.start_heartbeat_check())
            print("心跳检测任务已启动")

    async def connect(self, user_id: int, websocket: WebSocket):
        """处理新的WebSocket连接"""
        try:
            # 先检查是否有旧连接
            existing_connection = False
            old_ws = None
            
            async with self.connection_lock:
                if user_id in self.active_connections:
                    existing_connection = True
                    old_ws = self.active_connections[user_id]
            
            # 接受新连接
            await websocket.accept()
            
            # 如果有旧连接，在接受新连接后再关闭它
            if existing_connection and old_ws:
                try:
                    print(f"用户 {user_id} 有旧连接，关闭旧连接")
                    await old_ws.close(code=1000, reason="New connection established")
                except Exception as e:
                    print(f"关闭旧连接失败: {str(e)}")
            
            # 更新连接信息
            async with self.connection_lock:
                self.active_connections[user_id] = websocket
                self.last_heartbeat[user_id] = datetime.now()
                self.connection_status[user_id] = True  # 标记为活跃连接
            
            # 更新用户在线状态并通知好友
            await self._update_user_status(user_id, True)
            await self._notify_friends_status(user_id, True)
            
            # 发送连接成功确认
            success = await self.send_message(user_id, {"type": 0, "body": "connected"})
            if not success:
                print(f"警告: 无法向用户 {user_id} 发送连接确认消息")
                # 不要立即断开连接，因为这可能只是一个暂时的问题
            
            print(f"用户 {user_id} WebSocket连接已建立并确认")
            
        except Exception as e:
            self.connection_status[user_id] = False  # 连接出错，标记为非活跃
            print(f"WebSocket连接处理错误: {str(e)}")
            print(traceback.format_exc())
            # 如果发生异常，尝试断开可能已部分建立的连接
            try:
                # 使用安全的方式关闭连接
                if user_id in self.active_connections and self.active_connections[user_id] == websocket:
                    await websocket.close(code=1011, reason="Internal server error")
            except Exception:
                pass  # 忽略关闭连接时的错误
            # 返回False表示连接未成功建立
            return False
            
        return True

    async def disconnect(self, user_id: int):
        """处理WebSocket断开连接"""
        try:
            async with self.connection_lock:
                if user_id in self.active_connections:
                    # 通知好友用户离线
                    await self._notify_friends_status(user_id, False)
                    # 更新用户离线状态
                    await self._update_user_status(user_id, False)
                    
                    # 关闭连接并清理资源
                    try:
                        await self.active_connections[user_id].close()
                    except Exception as e:
                        print(f"关闭WebSocket连接失败: {str(e)}")
                        
                    # 清理连接相关数据
                    del self.active_connections[user_id]
                    if user_id in self.last_heartbeat:
                        del self.last_heartbeat[user_id]
                    self.connection_status[user_id] = False
        except Exception as e:
            print(f"断开连接处理错误: {str(e)}")
            print(traceback.format_exc())

    async def handle_message(self, user_id: int, data: Dict[str, Any]):
        """处理从客户端接收的消息"""
        try:
            if user_id not in self.active_connections:
                return False
                
            msg_type = data.get("type")
            if msg_type is None:
                return
            # # 处理心跳消息
            # if msg_type == 0:
            #     self.last_heartbeat[user_id] = datetime.now()
            #     await self.send_message(user_id, {"type": 0})
            #     return
            # 其他消息类型处理...
            handlers = {
                0: self.handle_heartbeat,
                1: self.handle_private_chat,
                2: self.handle_group_chat,
                3: self.handle_friend_apply,
                4: self.handle_pass_friend_apply,
                5: self.handle_reject_friend_apply,
                6: self.handle_delete_friend,
                11: self.handle_join_group,
                12: self.handle_exit_group,
                25: self.handle_group_apply,       # 群聊申请
                26: self.handle_group_apply_result # 群聊申请结果
            }
            
            if msg_type in handlers:
                await handlers[msg_type](user_id, data)
                
        except Exception as e:
            print(f"处理消息错误: {str(e)}")
            print(traceback.format_exc())

    async def send_message(self, user_id: int, message: Dict[str, Any]) -> bool:
        """发送WebSocket消息"""
        if user_id not in self.active_connections:
            print(f"用户 {user_id} 不在线，无法发送消息")
            return False
            
        # 如果连接状态标记为非活跃，尝试恢复
        if not self.connection_status.get(user_id, False):
            print(f"用户 {user_id} 连接状态标记为非活跃，尝试恢复")
            self.connection_status[user_id] = True
            
        try:
            # 获取连接
            websocket = self.active_connections[user_id]
            
            # 预处理消息格式，确保符合前端期望
            if message.get("type") in [1, 2]:  # 私聊或群聊消息
                # 确保body中的id字段是roomId
                if "body" in message and "roomId" in message["body"]:
                    if "id" not in message["body"] or message["body"]["id"] != message["body"]["roomId"]:
                        message["body"]["id"] = message["body"]["roomId"]
                        print(f"消息格式预处理: 设置id字段为roomId: {message['body']['roomId']}")
            
            # 提取消息ID用于去重
            message_id = None
            if message.get("type") in [1, 2] and "body" in message and "message" in message["body"] and "id" in message["body"]["message"]:
                message_id = message["body"]["message"]["id"]
                print(f"处理消息ID: {message_id}")
            
            try:
                # 发送消息
                await websocket.send_json(message)
                print(f"发送WebSocket消息给用户 {user_id}: type={message.get('type')}")
                
                # 更新心跳时间
                self.last_heartbeat[user_id] = datetime.now()
                
                # 如果是聊天消息，记录到消息队列以便重发
                if message.get("type") in [1, 2] and not message.get("_retrying"):  # 私聊或群聊消息
                    from app.services.message import MessageService
                    
                    # 检查队列中是否已经有相同ID的消息(去重)
                    if message_id:
                        existing_messages = [
                            msg for msg in MessageService._pending_messages[user_id] 
                            if msg.get("_message_id") == message_id
                        ]
                        
                        if existing_messages:
                            print(f"消息 {message_id} 已在队列中，跳过添加")
                        else:
                            message_copy = message.copy()
                            message_copy["_retrying"] = True
                            message_copy["_retry_count"] = 0
                            message_copy["_message_id"] = message_id
                            MessageService._pending_messages[user_id].append(message_copy)
                            print(f"消息 {message_id} 添加到队列用于潜在重发")
                    
                return True
                
            except Exception as e:
                print(f"发送WebSocket消息给用户 {user_id} 失败: {str(e)}")
                # 如果发送失败，将消息添加到队列中以便稍后重试
                if message.get("type") in [1, 2]:  # 私聊或群聊消息
                    from app.services.message import MessageService
                    
                    # 检查队列中是否已存在相同的消息
                    if message_id:
                        existing_messages = [
                            msg for msg in MessageService._pending_messages[user_id] 
                            if msg.get("_message_id") == message_id
                        ]
                        
                        if not existing_messages:
                            message_copy = message.copy()
                            message_copy["_retrying"] = True
                            message_copy["_retry_count"] = 0
                            message_copy["_message_id"] = message_id
                            MessageService._pending_messages[user_id].append(message_copy)
                            print(f"发送失败，消息 {message_id} 添加到队列")
                
                # 标记连接为不活跃
                self.connection_status[user_id] = False
                return False
                
        except Exception as e:
            print(f"发送WebSocket消息给用户 {user_id} 时发生异常: {str(e)}")
            print(traceback.format_exc())
            return False

    async def handle_heartbeat(self, user_id: int, data: Dict[str, Any]):
        """处理心跳消息"""
        self.last_heartbeat[user_id] = datetime.now()
        await self.send_message(user_id, {"type": 0})
        return

    async def start_heartbeat_check(self):
        """定期检查心跳状态，断开不活跃的连接"""
        try:
            while True:
                try:
                    now = datetime.now()
                    inactive_users = []
                    
                    async with self.connection_lock:
                        for user_id, last_time in list(self.last_heartbeat.items()):
                            # 超过60秒没有心跳，认为连接不活跃
                            if (now - last_time).total_seconds() > 60:
                                inactive_users.append(user_id)
                                
                    # 断开不活跃的连接
                    for user_id in inactive_users:
                        try:
                            print(f"用户 {user_id} 心跳超时，断开连接")
                            # 尝试发送一个PING测试连接
                            try:
                                if user_id in self.active_connections:
                                    await self.active_connections[user_id].send_text('{"type":0}')
                            except Exception:
                                # 如果发送失败，断开连接
                                await self.disconnect(user_id)
                                self.connection_status[user_id] = False
                                
                                # 将该用户的在线状态标记为离线
                                db = next(get_db())
                                user = db.query(User).filter(User.id == user_id).first()
                                if user:
                                    user.online = False
                                    user.last_at = now
                                    db.commit()
                        except Exception as e:
                            print(f"断开不活跃连接错误: {str(e)}")
                            
                except Exception as e:
                    print(f"心跳检测错误: {str(e)}")
                
                # 每15秒检查一次
                await asyncio.sleep(15)
        except asyncio.CancelledError:
            print("心跳检测任务已取消")
        except Exception as e:
            print(f"心跳检测循环错误: {str(e)}")
            print(traceback.format_exc())

    async def _update_user_status(self, user_id: int, online: bool):
        """更新用户在线状态"""
        db = next(get_db())
        try:
            user = db.query(User).filter(User.id == user_id).first()
            if user:
                user.online = online
                db.commit()
        except Exception as e:
            print(f"更新用户状态失败: {e}")
            db.rollback()
        finally:
            db.close()
        
    async def _notify_friends_status(self, user_id: int, online: bool):
        """通知好友用户状态变化"""
        db = next(get_db())
        try:
            # 获取用户的所有好友
            friends = db.query(Friend).filter(
                (Friend.user_id == user_id) | (Friend.friend_id == user_id)
            ).all()
            
            # 向在线好友发送状态通知
            for friend in friends:
                friend_id = friend.friend_id if friend.user_id == user_id else friend.user_id
                if friend_id in self.active_connections:
                    await self.send_message(friend_id, {
                        "type": 23 if online else 24,  # 23:上线 24:离线
                        "body": user_id
                    })
        except Exception as e:
            print(f"通知好友状态失败: {e}")
        finally:
            db.close()
    
    async def handle_private_chat(self, from_user_id: int, data: Dict[str, Any]):
        """处理私聊消息，包括文本、图片、文件"""
        try:
            room_id = data.get("roomId")
            message_content = data.get("content") or data.get("text")
            message_type = data.get("msgType", "text")
            
            if not room_id or not message_content:
                print("私聊消息格式错误，缺少必要参数")
                return
            
            db = next(get_db())
            try:
                # 验证房间访问权限
                room, room_member = MessageService.verify_room_access(db, room_id, from_user_id)
                
                if not room or room.type != 0:  # 确保是私聊类型
                    print(f"私聊房间不存在或类型错误: {room_id}")
                    return
                
                # 根据消息类型设置正确的type值
                msg_type = 0  # 默认文本消息
                if message_type == "image":
                    msg_type = 1
                elif message_type == "file":
                    msg_type = 2
                
                # 使用MessageService创建消息
                new_message = MessageService.create_message(
                    db=db,
                    room_id=room_id,
                    sender_id=from_user_id,
                    msg_type=msg_type,
                    content=message_content
                )
                
                # 获取发送者信息
                sender = db.query(User).filter(User.id == from_user_id).first()
                
                # 格式化消息
                message_detail = MessageService.format_message(new_message, sender)
                
                # 获取房间上下文
                friend, _ = MessageService.get_room_context(db, room, from_user_id)
                
                # 获取接收者ID
                target_user_id = room.user_id if room.user_id != from_user_id else room.friend_id
                
                # 构建标准格式的消息
                websocket_message = {
                    "type": 1,  # 私聊消息
                    "body": {
                        "id": room_id,  # 使用房间ID作为会话ID
                        "roomId": room_id,
                        "userId": target_user_id,
                        "message": message_detail,
                        "friend": friend
                    }
                }
                
                # 发送给接收者
                if target_user_id in self.active_connections:
                    print(f"发送私聊消息给在线用户 {target_user_id}")
                    success = await self.send_message(target_user_id, websocket_message)
                    if not success:
                        print(f"发送私聊消息给用户 {target_user_id} 失败，将消息加入队列")
                        MessageService._pending_messages[target_user_id].append(websocket_message)
                else:
                    # 将消息加入离线队列
                    print(f"用户 {target_user_id} 不在线，消息加入队列")
                    MessageService._pending_messages[target_user_id].append(websocket_message)
                
                # 响应发送者
                await self.send_message(from_user_id, {
                    "type": 1,  # 私聊消息
                    "body": {
                        "id": room_id,
                        "roomId": room_id,
                        "userId": from_user_id,
                        "message": message_detail,
                        "friend": friend
                    }
                })
                
            except Exception as e:
                print(f"处理私聊消息错误: {str(e)}")
                print(traceback.format_exc())
                db.rollback()
            finally:
                db.close()
            
        except Exception as e:
            print(f"处理私聊消息时发生异常: {str(e)}")
            print(traceback.format_exc())

    async def _handle_file_message(self, from_user_id: int, data: Dict[str, Any], file_type: str):
        """处理图片或文件消息"""
        try:
            room_id = data.get("roomId")
            file_url = data.get("fileUrl")
            file_name = data.get("fileName") if file_type == "file" else None
            
            if not room_id or not file_url:
                print("文件消息格式错误，缺少必要参数")
                return
            
            db = next(get_db())
            try:
                # 验证房间访问权限
                room, room_member = MessageService.verify_room_access(db, room_id, from_user_id)
                
                if not room or room.type != 0:  # 确保是私聊类型
                    print(f"私聊房间不存在或类型错误: {room_id}")
                    return
                
                # 设置消息类型
                msg_type = 1 if file_type == "image" else 2  # 1:图片 2:文件
                
                # 使用MessageService创建消息
                new_message = MessageService.create_message(
                    db=db,
                    room_id=room_id,
                    sender_id=from_user_id,
                    msg_type=msg_type,
                    content=file_url
                )
                
                # 获取发送者信息
                sender = db.query(User).filter(User.id == from_user_id).first()
                
                # 格式化消息
                message_detail = MessageService.format_message(new_message, sender)
                if file_name:
                    message_detail["fileName"] = file_name
                
                # 获取房间上下文
                friend, _ = MessageService.get_room_context(db, room, from_user_id)
                
                # 获取接收者ID
                target_user_id = room.user_id if room.user_id != from_user_id else room.friend_id
                
                # 使用MessageService发送消息
                success = await MessageService.notify_message(
                    self,  # 传入ws_handler实例
                    target_user_id,
                    room_id,
                    message_detail,
                    friend,
                    is_group=False
                )
                
                if not success:
                    print(f"发送文件消息给用户 {target_user_id} 失败，消息已加入重试队列")
                
                # 响应发送者
                await self.send_message(from_user_id, {
                    "type": 1,  # 私聊消息
                    "body": {
                        "id": room_id,
                        "roomId": room_id,
                        "userId": from_user_id,
                        "message": message_detail,
                        "friend": friend
                    }
                })
                
            except Exception as e:
                print(f"处理文件消息错误: {str(e)}")
                print(traceback.format_exc())
                db.rollback()
            finally:
                db.close()
            
        except Exception as e:
            print(f"处理文件消息时发生异常: {str(e)}")
            print(traceback.format_exc())

    async def handle_group_chat(self, from_user_id: int, data: Dict[str, Any]):
        """处理群聊消息"""
        db = next(get_db())
        try:
            # 添加详细日志
            print(f"处理群聊消息: user_id={from_user_id}, data={data}")
            
            # 适配前端消息格式
            room_id = data.get("roomId") or data.get("group_id")
            message_content = data.get("content") or data.get("text")
            message_type = data.get("type", 0)  # 默认文本消息
            
            if not room_id or not message_content:
                print("群聊消息格式错误，缺少必要参数")
                return
                
            # 验证房间访问权限
            room = db.query(Room).filter(Room.id == room_id).first()
            if not room or room.type != 1:  # 确保是群聊类型
                print(f"群聊房间不存在或类型错误: {room_id}")
                return
            
            # 验证发送者权限
            room_member = db.query(RoomMember).filter(
                RoomMember.room_id == room_id,
                RoomMember.user_id == from_user_id
            ).first()
            
            if not room_member:
                print(f"用户 {from_user_id} 无权访问群聊 {room_id}")
                return
            
            # 创建消息
            new_message = DBMessage(
                room_id=room_id,
                sender_id=from_user_id,
                type=str(message_type),
                content=message_content,
                status=1,
                created_at=datetime.now()
            )
            db.add(new_message)
            db.commit()
            db.refresh(new_message)
            
            # 获取发送者信息
            sender = db.query(User).filter(User.id == from_user_id).first()
            
            # 格式化消息
            from app.services.message import MessageService
            message_detail = MessageService.format_message(new_message, sender)
            
            # 确保online字段是数字类型
            if "online" in message_detail and isinstance(message_detail["online"], bool):
                message_detail["online"] = 1 if message_detail["online"] else 0
            
            # 获取房间上下文
            _, group = MessageService.get_room_context(db, room, from_user_id)
            
            # 获取所有房间成员
            room_members = db.query(RoomMember).filter(
                RoomMember.room_id == room_id
            ).all()

            print(f"群聊 {room_id} 有 {len(room_members)} 名成员需要发送消息")

            # 构建标准格式的消息
            websocket_message = {
                "type": 2,  # 群聊消息
                "body": {
                    "id": room_id,  # 使用房间ID作为会话ID
                    "roomId": room_id,
                    "message": message_detail,
                    "group": group
                }
            }

            # 发送给所有群成员（包括发送者自己）
            sent_users = set()  # 用于跟踪已发送消息的用户
            for member in room_members:
                target_user_id = member.user_id
                
                # 跳过已发送的用户
                if target_user_id in sent_users:
                    continue
                
                sent_users.add(target_user_id)
                
                # 为每个用户设置特定的userId
                current_message = {
                    **websocket_message,
                    "body": {
                        **websocket_message["body"],
                        "userId": target_user_id
                    }
                }
                
                if target_user_id in self.active_connections:
                    print(f"发送群聊消息给在线用户 {target_user_id}")
                    success = await self.send_message(target_user_id, current_message)
                    if not success:
                        print(f"发送群聊消息给用户 {target_user_id} 失败，将消息加入队列")
                        from app.services.message import MessageService
                        MessageService._pending_messages[target_user_id].append(current_message)
                else:
                    # 将消息加入离线队列
                    print(f"用户 {target_user_id} 不在线，消息加入队列")
                    from app.services.message import MessageService
                    MessageService._pending_messages[target_user_id].append(current_message)
            
            # 响应发送者
            await self.send_message(from_user_id, {
                "type": 2,  # 群聊消息
                "body": {
                    "id": room_id,
                    "roomId": room_id,
                    "userId": from_user_id,
                    "message": message_detail,
                    "group": group
                }
            })
                
        except Exception as e:
            print(f"处理群聊消息错误: {str(e)}")
            print(traceback.format_exc())
            db.rollback()

    async def handle_friend_apply(self, from_user_id: int, data: Dict[str, Any]):
        """处理好友申请"""
        db = next(get_db())
        try:
            to_user_id = data.get("to_user_id")
            content = data.get("content", "请求添加您为好友")
            
            # 创建好友申请记录
            apply = Apply(
                user_id=from_user_id,
                target_id=to_user_id,
                content=content,
                status=0  # 待处理
            )
            db.add(apply)
            db.commit()
            db.refresh(apply)
            # 发送给目标用户
            if to_user_id in self.active_connections:
                await self.send_message(to_user_id, {
                    "type": 3,
                    "body": {
                        "id": apply.id,
                        "user_id": from_user_id,
                        "content": content,
                        "status": 0,
                        "created_at": str(apply.created_at)
                    }
                })
        except Exception as e:
            print(f"处理好友申请失败: {e}")
            db.rollback()
        finally:
            db.close()
    
    async def handle_pass_friend_apply(self, from_user_id: int, data: Dict[str, Any]):
        """处理通过好友申请"""
        db = next(get_db())
        try:
            apply_id = data.get("apply_id")
            apply = db.query(Apply).filter(Apply.id == apply_id).first()
            if not apply or apply.target_id != from_user_id:
                return
                
            # 更新申请状态
            apply.status = 1  # 已通过
            db.commit()
            
            # 创建好友关系
            friend = Friend(
                user_id=apply.user_id,
                friend_id=apply.target_id
            )
            db.add(friend)
            db.commit()
            
            try:
                # 获取通过者（当前用户）的信息
                approver = db.query(User).filter(User.id == from_user_id).first()
                
                # 获取申请者的信息
                applicant = db.query(User).filter(User.id == apply.user_id).first()
                
                if approver and applicant:
                    # 构建好友信息
                    approver_info = {
                        "id": friend.id,
                        "userId": approver.id,
                        "nickname": approver.nickname,
                        "sex": approver.sex,
                        "online": 1 if approver.online else 0,
                        "email": approver.email,
                        "last_at": approver.last_at,
                        "created_at": approver.created_at
                    }
                    
                    applicant_info = {
                        "id": friend.id,
                        "userId": applicant.id,
                        "nickname": applicant.nickname,
                        "sex": applicant.sex,
                        "online": 1 if applicant.online else 0,
                        "email": applicant.email,
                        "last_at": applicant.last_at,
                        "created_at": applicant.created_at
                    }
                    
                    # 通知申请人（发送完整的好友信息）
                    if apply.user_id in self.active_connections:
                        await self.send_message(apply.user_id, {
                            "type": 4,
                            "body": {
                                "id": friend.id,
                                "name": "我的好友",  # 默认分组名称
                                "fixed": 1,
                                "friends": [approver_info]  # 将通过者的信息发送给申请者
                            }
                        })
                    
                    # 通知通过者（可选，如果需要实时更新通过者的好友列表）
                    if from_user_id in self.active_connections:
                        await self.send_message(from_user_id, {
                            "type": 4,
                            "body": {
                                "id": friend.id,
                                "name": "我的好友",
                                "fixed": 1,
                                "friends": [applicant_info]  # 将申请者的信息发送给通过者
                            }
                        })
            except Exception as e:
                print(f"处理好友信息通知失败: {e}")
                print(traceback.format_exc())
                
        except Exception as e:
            print(f"处理通过好友申请失败: {e}")
            print(traceback.format_exc())
            db.rollback()
        finally:
            db.close()
    
    async def handle_reject_friend_apply(self, from_user_id: int, data: Dict[str, Any]):
        """处理拒绝好友申请"""
        db = next(get_db())
        try:
            apply_id = data.get("apply_id")
            apply = db.query(Apply).filter(Apply.id == apply_id).first()
            if not apply or apply.target_id != from_user_id:
                return
                
            # 更新申请状态
            apply.status = 2  # 已拒绝
            db.commit()
            
            # 通知申请人
            if apply.user_id in self.active_connections:
                await self.send_message(apply.user_id, {
                    "type": 5,
                    "body": {
                        "id": apply.id,
                        "friend_id": from_user_id
                    }
                })
        except Exception as e:
            print(f"处理拒绝好友申请失败: {e}")
            db.rollback()
        finally:
            db.close()
        
    async def handle_delete_friend(self, from_user_id: int, data: Dict[str, Any]):
        """处理删除好友"""
        db = next(get_db())
        try:
            friend_id = data.get("friend_id")
            friend = db.query(Friend).filter(
                ((Friend.user_id == from_user_id) & (Friend.friend_id == friend_id)) |
                ((Friend.user_id == friend_id) & (Friend.friend_id == from_user_id))
            ).first()
            
            if friend:
                db.delete(friend)
                db.commit()
                
                # 通知被删除的好友
                if friend_id in self.active_connections:
                    await self.send_message(friend_id, {
                        "type": 6,
                        "body": from_user_id
                    })
        except Exception as e:
            print(f"处理删除好友失败: {e}")
            db.rollback()
        finally:
            db.close()

    async def handle_join_group(self, from_user_id: int, data: Dict[str, Any]):
        """处理加入群组"""
        db = next(get_db())
        try:
            room_id = data.get("room_id")
            room = db.query(Room).filter(Room.id == room_id).first()
            if not room:
                return
                
            # 添加群成员
            if from_user_id not in [m.id for m in room.members]:
                room.members.append(db.query(User).filter(User.id == from_user_id).first())
                db.commit()
                
                # 通知群成员
                for member in room.members:
                    if member.id != from_user_id and member.id in self.active_connections:
                        await self.send_message(member.id, {
                            "type": 11,
                            "body": {
                                "room_id": room_id,
                                "user_id": from_user_id
                            }
                        })
        except Exception as e:
            print(f"处理加入群组失败: {e}")
            db.rollback()
        finally:
            db.close()
        
    async def handle_exit_group(self, from_user_id: int, data: Dict[str, Any]):
        """处理退出群组"""
        db = next(get_db())
        try:
            room_id = data.get("room_id")
            room = db.query(Room).filter(Room.id == room_id).first()
            if not room:
                return
                
            # 移除群成员
            user = db.query(User).filter(User.id == from_user_id).first()
            if user in room.members:
                room.members.remove(user)
                db.commit()
                
                # 通知群成员
                for member in room.members:
                    if member.id in self.active_connections:
                        await self.send_message(member.id, {
                            "type": 12,
                            "body": {
                                "room_id": room_id,
                                "user_id": from_user_id
                            }
                        })
        except Exception as e:
            print(f"处理退出群组失败: {e}")
            db.rollback()
        finally:
            db.close()

    async def handle_user_online(self, user_id: int, data: Dict[str, Any]):
        """处理用户上线"""
        db = next(get_db())
        try:
            # 更新用户在线状态
            user = db.query(User).filter(User.id == user_id).first()
            if user:
                user.online = True
                db.commit()
        except Exception as e:
            print(f"处理用户上线失败: {e}")
            db.rollback()
        finally:
            db.close()
        
    async def handle_user_offline(self, user_id: int, data: Dict[str, Any]):
        """处理用户离线"""
        db = next(get_db())
        try:
            # 更新用户离线状态
            user = db.query(User).filter(User.id == user_id).first()
            if user:
                user.online = False
                db.commit()
        except Exception as e:
            print(f"处理用户离线失败: {e}")
            db.rollback()
        finally:
            db.close()

    async def handle_group_apply(self, from_user_id: int, data: Dict[str, Any]):
        """处理群聊申请"""
        # 这个函数只是为了处理从客户端发送的群聊申请消息
        # 实际的申请处理逻辑已经在 RoomService.join_group 中完成
        print(f"收到群聊申请消息: user_id={from_user_id}, data={data}")
        
    async def handle_group_apply_result(self, from_user_id: int, data: Dict[str, Any]):
        """处理群聊申请结果"""
        # 这个函数只是为了处理从客户端发送的群聊申请结果消息
        # 实际的结果处理逻辑已经在 RoomService.review_join_apply 中完成
        print(f"收到群聊申请结果消息: user_id={from_user_id}, data={data}")
